<template>
  <view class="travel-page">
    <!-- 顶部标题和搜索 -->
    <view class="page-header">
      <text class="page-title">发现精彩</text>
      
      <!-- 搜索框和搜索按钮 -->
      <view class="search-container">
        <view class="search-box">
          <input 
            class="search-input" 
            v-model="searchKeyword" 
            placeholder="搜索游记或标签"
            confirm-type="search"
            @confirm="handleSearch"
          />
          <text class="search-icon iconfont icon-search"></text>
          <text v-if="searchKeyword" class="clear-icon" @click="clearSearch">×</text>
        </view>
        <view class="search-btn" @click="handleSearch">
          <text class="btn-text">搜索</text>
        </view>
      </view>
      
      <!-- 热门标签 -->
      <scroll-view v-if="!isSearchMode" class="tags-scroll" scroll-x>
        <view class="tags-container">
          <view 
            class="tag-item" 
            v-for="tag in hotTags" 
            :key="tag.id"
            @click="searchByTag(tag.name)"
          >
            <text class="tag-name">#{{tag.name}}</text>
          </view>
        </view>
      </scroll-view>
      
      <!-- 搜索结果提示 -->
      <view v-if="isSearchMode" class="search-result-info">
        <text class="result-text">{{searchResultText}}</text>
        <text class="back-to-all" @click="clearSearch">返回全部</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view class="content" scroll-y @scrolltolower="loadMore" refresher-enabled @refresherrefresh="refreshList" :refresher-triggered="refreshing">
      <!-- 空状态 -->
      <view v-if="travelList.length === 0 && !loading" class="empty-state">
        <text class="empty-text">暂无游记，快来分享你的旅行故事吧</text>
        <view class="create-btn" @click="navigateToPublish">发布游记</view>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="loading && !refreshing" class="loading-state">
        <view class="loading-content">
          <text class="loading-icon">🔄</text>
          <text class="loading-text">正在加载精彩内容...</text>
        </view>
      </view>
      
      <!-- 游记列表 -->
      <view v-if="travelList.length > 0" class="travel-list">
        <view 
          v-for="(item, index) in travelList" 
          :key="item.id" 
          class="travel-card"
        >
          <view class="card-inner">
            <view class="user-info" >
              <image class="avatar" :src="item.userAvatar" mode="aspectFill"></image>
              <text class="nickname">{{item.userNickname}}</text>
              <text class="time">{{formatTime(item.createdAt)}}</text>
            </view>
            <view class="travel-content">
              <text class="content-text">{{item.content}}</text>
            </view>
            <view class="travel-images" @click="navigateToDetail(item.id)" v-if="item.image">
              <view class="image-grid" :class="getImageGridClass(item.image)">
                <image v-for="(url, imgIndex) in item.image.split(',')" 
                       :key="imgIndex" 
                       :src="url" 
                       mode="aspectFill"
                      >
                </image>
              </view>
            </view>
            <view class="travel-stats">
              <view class="stat-item">
                <text class="iconfont icon-liulanliang"></text>
                <text class="stat-value">{{item.views}}</text>
              </view>
              <view class="stat-item" @click.stop="handleLike(item)">
                <text class="iconfont icon-icon" :class="{'active': item.liked}"></text>
                <text class="stat-value" :class="{'active': item.liked}">{{item.likes}}</text>
              </view>
              <view class="stat-item" @click.stop="handleFavorite(item)">
                <text class="iconfont icon-shoucang" :class="{'active': item.favorited}"></text>
                <text class="stat-value" :class="{'active': item.favorited}">{{item.favorites}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="hasMoreData && travelList.length > 0" class="load-more">
        <text class="load-more-text">加载更多...</text>
      </view>
      
      <!-- 无更多数据 -->
      <view v-if="!hasMoreData && travelList.length > 0" class="no-more">
        <text class="no-more-text">没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { 
  getTravelList, 
  likeTravel, 
  unlikeTravel, 
  favoriteTravel, 
  unfavoriteTravel, 
  increaseTravelView
} from '@/api/travel'
import { getHotTags, searchTags } from '@/api/tag'
// 响应式数据
const travelList = ref([])
const loading = ref(false)
const refreshing = ref(false)
const hasMoreData = ref(true)
const currentUser = ref(null)
const TravelParams = ref({
  page: 0,
  size: 10,
  keyword: '',
  currentUserId: null
})

// 添加搜索相关的响应式数据
const searchKeyword = ref('')
const hotTags = ref([])
const isSearchMode = ref(false)
const searchTagId = ref(null)

// 计算属性：搜索结果文本
const searchResultText = computed(() => {
  if (searchTagId.value) {
    return `#${searchKeyword.value} 的相关游记`
  } else if (searchKeyword.value) {
    return `"${searchKeyword.value}" 的搜索结果`
  }
  return ''
})

// 初始化用户信息
const initUserInfo = () => {
  try {
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      currentUser.value = userInfo
      TravelParams.value.currentUserId = userInfo.id
    }
  } catch (err) {
    console.error('获取用户信息失败:', err)
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  // 一小时内
  if (diff < 3600000) {
    const minutes = Math.floor(diff / 60000)
    return `${minutes}分钟前`
  }
  
  // 一天内
  if (diff < 86400000) {
    const hours = Math.floor(diff / 3600000)
    return `${hours}小时前`
  }
  
  // 一周内
  if (diff < 604800000) {
    const days = Math.floor(diff / 86400000)
    return `${days}天前`
  }
  
  // 显示日期
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 获取游记列表
const fetchTravelList = async (loadMore = false) => {
  if (loading.value) return
  
  loading.value = true
  
  try {
    // 添加标签ID参数
    if (searchTagId.value) {
      TravelParams.value.tagId = searchTagId.value
    } else {
      TravelParams.value.tagId = null
    }
    
    // 获取游记列表数据
    const res = await getTravelList(TravelParams.value)
    
    if (res.code === 200) {
      if (loadMore) {
        travelList.value = [...travelList.value, ...res.data.content]
      } else {
        travelList.value = res.data.content
      }
      
      // 判断是否还有更多数据
      hasMoreData.value = !res.data.last
      
      console.log('游记列表加载成功:', res.data)
    } else {
      uni.showToast({
        title: res.message || '获取游记列表失败',
        icon: 'none'
      })
    }
  } catch (err) {
    console.error('获取游记列表出错:', err)
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 刷新列表
const refreshList = () => {
  refreshing.value = true
  TravelParams.value.page = 0
  fetchTravelList()
}

// 加载更多
const loadMore = () => {
  if (!hasMoreData.value || loading.value) return
  
  TravelParams.value.page++
  fetchTravelList(true)
}

// 处理点赞
const handleLike = async (item) => {
  if (!currentUser.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  try {
    const userId = currentUser.value.id 
    
    if (item.liked) {
      // 取消点赞
      await unlikeTravel(item.id, userId)
      item.likes--
      item.liked = false
    } else {
      // 点赞
      await likeTravel(item.id, userId)
      item.likes++
      item.liked = true
    }
  } catch (err) {
    console.error('操作失败:', err)
    uni.showToast({
      title: '操作失败，请稍后重试',
      icon: 'none'
    })
  }
}

// 处理收藏
const handleFavorite = async (item) => {
  if (!currentUser.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  try {
    const userId = currentUser.value.id
    
    if (item.favorited) {
      // 取消收藏
      await unfavoriteTravel(item.id, userId)
      item.favorites--
      item.favorited = false
    } else {
      // 收藏
      await favoriteTravel(item.id, userId)
      item.favorites++
      item.favorited = true
    }
  } catch (err) {
    console.error('操作失败:', err)
    uni.showToast({
      title: '操作失败，请稍后重试',
      icon: 'none'
    })
  }
}

// 跳转到游记详情页
const navigateToDetail = async (id) => {
  try {
    // 增加浏览量
    await increaseTravelView(id)
    
    // 找到对应的游记，本地更新浏览量
    const travel = travelList.value.find(item => item.id === id)
    if (travel) {
      travel.views++
    }
    
    // 跳转到详情页
    uni.navigateTo({
      url: `/pages/discovery/travel-detail?id=${id}`
    })
  } catch (err) {
    console.error('增加浏览量失败:', err)
    // 仍然跳转到详情页
    uni.navigateTo({
      url: `/pages/discovery/travel-detail?id=${id}`
    })
  }
}

// 跳转到用户详情页
const navigateToUserDetail = (userId) => {
  if (!userId) return
  
  if (currentUser.value && userId === currentUser.value.id) {
    // 如果是当前用户，跳转到个人中心
    uni.switchTab({
      url: '/pages/usercenter/index'
    })
  } else {
    // 如果是其他用户，跳转到用户详情页
    uni.navigateTo({
      url: `/pages/discovery/user-detail?userId=${userId}`
    })
  }
}

// 跳转到发布页面
const navigateToPublish = () => {
  if (!currentUser.value) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    })
    return
  }
  
  uni.navigateTo({
    url: '/package-discovery/pages/public-travel'
  })
}

// 获取热门标签
const fetchHotTags = async () => {
  try {
    const res = await getHotTags({ page: 0, size: 10 })
    if (res.code === 200) {
      hotTags.value = res.data.content
    }
  } catch (err) {
    console.error('获取热门标签失败:', err)
  }
}

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value.trim()) {
    if (isSearchMode.value) {
      clearSearch()
    }
    return
  }
  
  isSearchMode.value = true
  searchTagId.value = null
  
  // 重置页码
  TravelParams.value.page = 0
  TravelParams.value.keyword = searchKeyword.value.trim()
  
  // 加载搜索结果
  fetchTravelList()
}

// 根据标签搜索
const searchByTag = async (tagName) => {
  searchKeyword.value = tagName
  isSearchMode.value = true
  
  // 查找标签ID
  try {
    const res = await searchTags(tagName)
    if (res.code === 200 && res.data.content.length > 0) {
      searchTagId.value = res.data.content[0].id
    } else {
      searchTagId.value = null
    }
  } catch (err) {
    console.error('搜索标签失败:', err)
    searchTagId.value = null
  }
  
  // 重置页码
  TravelParams.value.page = 0
  TravelParams.value.keyword = tagName
  TravelParams.value.tagId = searchTagId.value
  
  // 加载搜索结果
  fetchTravelList()
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
  isSearchMode.value = false
  searchTagId.value = null
  
  // 重置搜索参数
  TravelParams.value.page = 0
  TravelParams.value.keyword = ''
  TravelParams.value.tagId = null
  
  // 重新加载游记列表
  fetchTravelList()
}

// 预览图片
const previewImages = (imageStr, currentIndex) => {
  const urls = imageStr.split(',')
  uni.previewImage({
    urls,
    current: currentIndex
  })
}

// 获取图片网格的类名
const getImageGridClass = (imageStr) => {
  const count = imageStr.split(',').length
  if (count === 1) return 'single'
  if (count === 2) return 'double'
  if (count === 3) return 'triple'
  if (count === 4) return 'quad'
  return 'multi'
}

// 生命周期钩子
onMounted(() => {
  initUserInfo()
  fetchTravelList()
  fetchHotTags()
})

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  if (!newVal && isSearchMode.value) {
    clearSearch()
  }
})
</script>

<style lang="scss" scoped>
.travel-page {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding-bottom: 30rpx;

  .page-header {
    padding: 30rpx;
    display: flex;
    flex-direction: column;
    
    .page-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .publish-btn {
      background-color: #42b983;
      padding: 12rpx 30rpx;
      border-radius: 30rpx;
      
      .publish-text {
        color: white;
        font-size: 28rpx;
        font-weight: 500;
      }
    }
  }

  .content {
    height: calc(100vh - 240rpx);
    
    .empty-state {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 100rpx 30rpx;
      
      .empty-image {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 30rpx;
      }
      
      .empty-text {
        font-size: 28rpx;
        color: #999;
        margin-bottom: 40rpx;
      }
      
      .create-btn {
        background-color: #42b983;
        color: white;
        font-size: 28rpx;
        padding: 20rpx 60rpx;
        border-radius: 40rpx;
      }
    }
    
    .loading-state {
      padding: 40rpx 0;
      
      .loading-content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        
        .loading-icon {
          font-size: 40rpx;
          margin-bottom: 20rpx;
          animation: rotate 1s linear infinite;
        }
        
        .loading-text {
          font-size: 28rpx;
          color: #999;
        }
      }
    }
    
    .travel-list {
      padding: 0 20rpx;
      
      .travel-card {
        background-color: white;
        border-radius: 16rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
        overflow: hidden;
        
        .card-inner {
          padding: 30rpx;
          
          .user-info {
            display: flex;
            align-items: center;
            margin-bottom: 20rpx;
            
            .avatar {
              width: 80rpx;
              height: 80rpx;
              border-radius: 50%;
              margin-right: 16rpx;
            }
            
            .nickname {
              font-size: 28rpx;
              font-weight: 500;
              color: #333;
              flex: 1;
            }
            
            .time {
              font-size: 24rpx;
              color: #999;
            }
          }
          
          .travel-content {
            margin-bottom: 20rpx;
            
            .content-text {
              font-size: 30rpx;
              color: #333;
              line-height: 1.6;
            }
          }
          
          .travel-images {
            margin: 20rpx 0;
            
            .image-grid {
              display: grid;
              gap: 6rpx;
              
              &.single {
                grid-template-columns: 1fr;
                
                image {
                  height: 500rpx;
                  border-radius: 12rpx;
                }
              }
              
              &.double {
                grid-template-columns: repeat(2, 1fr);
                
                image {
                  height: 400rpx;
                  border-radius: 12rpx;
                }
              }
              
              &.triple {
                grid-template-columns: repeat(3, 1fr);
                
                image {
                  height: 300rpx;
                  border-radius: 12rpx;
                }
              }
              
              &.quad {
                grid-template-columns: repeat(2, 1fr);
                grid-template-rows: repeat(2, 1fr);
                
                image {
                  height: 300rpx;
                  border-radius: 12rpx;
                }
              }
              
              &.multi {
                grid-template-columns: repeat(3, 1fr);
                
                image {
                  height: 240rpx;
                  border-radius: 12rpx;
                }
              }
              
              image {
                width: 100%;
                object-fit: cover;
              }
            }
          }
          
          .travel-stats {
            display: flex;
            align-items: center;
            
            .stat-item {
              display: flex;
              align-items: center;
              margin-right: 40rpx;
              padding: 10rpx 0;
              
              .iconfont {
                font-size: 32rpx;
                color: #999;
                margin-right: 8rpx;
                transition: color 0.3s;
                
                &.active {
                  color: #42b983;
                }
              }
              
              .stat-value {
                font-size: 26rpx;
                color: #999;
                transition: color 0.3s;
                
                &.active {
                  color: #42b983;
                }
              }
            }
          }
        }
      }
    }
    
    .load-more, .no-more {
      text-align: center;
      padding: 30rpx 0;
      
      .load-more-text, .no-more-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 搜索框样式 */
.search-container {
  display: flex;
  width: 100%;
  height: 70rpx;
  margin-bottom: 20rpx;
}

.search-box {
  flex: 1;
  position: relative;
  height: 100%;
  background-color: #f5f5f5;
  border-radius: 35rpx 0 0 35rpx;
  padding: 0 70rpx 0 30rpx;
  box-sizing: border-box;
}

.search-input {
  width: 100%;
  height: 100%;
  font-size: 28rpx;
  color: #333;
}

.search-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32rpx;
  color: #999;
}

.clear-icon {
  position: absolute;
  right: 70rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 32rpx;
  color: #999;
  z-index: 2;
}

.search-btn {
  width: 120rpx;
  height: 100%;
  background-color: #42b983;
  border-radius: 0 35rpx 35rpx 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  color: white;
  font-size: 28rpx;
  font-weight: 500;
}

/* 分类标签样式 */
.category-tabs {
  display: flex;
  margin-bottom: 20rpx;
}

.tab-item {
  padding: 10rpx 40rpx;
  margin-right: 20rpx;
  border-radius: 30rpx;
  background-color: #f5f5f5;
  transition: all 0.3s ease;
}

.tab-item.active {
  background-color: #42b983;
}

.tab-text {
  font-size: 28rpx;
  color: #666;
  transition: color 0.3s ease;
}

.tab-item.active .tab-text {
  color: #fff;
  font-weight: 500;
}

/* 标签样式 */
.tags-scroll {
  width: 100%;
  white-space: nowrap;
  margin-bottom: 20rpx;
}

.tags-container {
  display: inline-flex;
  padding: 0 10rpx;
}

.tag-item {
  display: inline-block;
  padding: 6rpx 20rpx;
  margin: 0 10rpx;
  background-color: #f0f8ff;
  border-radius: 30rpx;
}

.tag-name {
  font-size: 24rpx;
  color: #3498db;
}

/* 搜索结果信息 */
.search-result-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  margin-bottom: 20rpx;
}

.result-text {
  font-size: 26rpx;
  color: #666;
}

.back-to-all {
  font-size: 26rpx;
  color: #3498db;
}
</style>